package com.hele.sts.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletContext;

import com.hele.sts.dao.*;
import com.hele.sts.pub.encrypt.BCryptPasswordEncoder;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hele.sts.pub.FileManager;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.hele.sts.pub.Constants;


/**
 * @author Administrator
 */
@Controller
public class LoginAction implements Action {

	private static final Logger logger = LoggerFactory.getLogger(LoginAction.class);



	private String userName;
	private String passWord;
	private String action;
	private String tipInfo;
	private String captcha;
	private boolean showCaptcha;

	@Autowired
	private XtUserLoginDao xtUserLoginDao;

    @Autowired
    private XtLogDao xtLogDao;

	@Override
	public String execute() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		Map session = ctx.getSession();
		if (this.action == null) {
			
			String userId = (String)session.get("userid");
			if(userId!=null){
				QUser qUser = QUserDao.load(userId);
				if ("1".equals(qUser.getYhlx())) {
					return "queryQy";
				} else {
					return "queryQyEk";
				}
			}
			return "login";
		}
		
		if ("login".equalsIgnoreCase(this.action)) {
			String userId = (String)session.get("userid");
			if(userId!=null){
				QUser qUser = QUserDao.load(userId);
				if ("1".equals(qUser.getYhlx())) {
					return "queryQy";
				} else {
					return "queryQyEk";
				}
			}
			
			
			if (userName == null) {
				this.tipInfo = "请输入用户名！";
				return "login";
			}
			if (passWord == null) {
				this.tipInfo = "请输入密码！";
				return "login";
			}
			XtUserLogin xtUserLogin = xtUserLoginDao.queryByUsername(userName);
			int loginErrorCount = 0;
			if(xtUserLogin!=null){
				int loginState = xtUserLogin.getLoginState();
				if(Constants.LOGIN_STATE_LOCKED==loginState){
				    Date allowLoginTime = xtUserLogin.getAllowLoginTime();
					if(allowLoginTime!=null && new Date().before(allowLoginTime)){
						tipInfo = "您的账户登录错误次数太多，请等待一段时间再试";
						return "login";
					}else{
                        //晚于允许访问时间，允许继续尝试，或允许时间为空
					}
				}
				loginErrorCount = xtUserLogin.getLoginErrorCount();
				if(loginErrorCount>= Constants.USER_LOCK_TIMES ){

				}
			}else {

            }

			//QUser qUser = QUserDao.login(userName, passWord);

			QUser qUser = QUserDao.loadBy(userName);
			if(qUser==null){
				tipInfo = "请输入正确的用户名和密码！";
				return "login";
			}
			String dbPass = qUser.getPasswd();
			BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
			boolean matched = passwordEncoder.matches(passWord,dbPass);


			//20180927 todo 登录错误次数控制，包括3次需验证码，5次锁定半小时

//			失败失败－－累加结果 >＝3 则 misstime ＝ now+30分钟 （missnumber清0）
//			登录成功  missnumber清0
//
//			登录时   if（misstime>now）则不允许登录

            //登录失败
			if (!matched) {
				this.tipInfo = "请输入正确的用户名和密码！";

				if(xtUserLogin==null){
					xtUserLogin = new XtUserLogin();
					xtUserLogin.setUsername(userName);
					xtUserLogin.setLoginErrorCount(1);
					xtUserLogin.setLoginState(Constants.LOGIN_STATE_NOT_LOGIN);
					xtUserLogin.setLastLoginTime(new Date(System.currentTimeMillis()));
					xtUserLoginDao.insert(xtUserLogin);
				}else {
					loginErrorCount = xtUserLogin.getLoginErrorCount();
                    loginErrorCount += 1;
					if(loginErrorCount>=Constants.USER_LOCK_TIMES){
                        xtUserLogin.setLoginState(Constants.LOGIN_STATE_LOCKED);
                        //允许登录时间为从当前服务器时间开始
                        Date allowData = DateUtils.addMinutes(new Date(System.currentTimeMillis()),Constants.LOGIN_LOCKED_TIME);
                        xtUserLogin.setAllowLoginTime(allowData);
                        this.tipInfo = "您输入的错误次数太多，请稍候再试！";
					}
					if(loginErrorCount>=Constants.USER_VERIFY_TIMES){
					    //需要显示验证码
                        showCaptcha = true;
					}else{

					}
                    xtUserLogin.setLoginErrorCount(loginErrorCount);
                    xtUserLoginDao.update(xtUserLogin);
				}
				XtLog log = new XtLog();
				log.setClassname(this.getClass().getName());
				log.setMethod("execute");
				log.setLogtype("业务日志");
				log.setLogname("登录失败");
				log.setCreatetime(new Date(System.currentTimeMillis()));
				log.setSucceed("成功");
				log.setMessage("帐号:"+userName);
                xtLogDao.insert(log);
				return "login";
			}
                XtLog log = new XtLog();
                log.setClassname(this.getClass().getName());
                log.setMethod("execute");
                log.setLogtype("业务日志");
                log.setLogname("登录成功");
                log.setCreatetime(new Date(System.currentTimeMillis()));
                log.setSucceed("成功");
                log.setMessage("帐号:"+userName);
                xtLogDao.insert(log);


            if(xtUserLogin==null){
                xtUserLogin = new XtUserLogin();
                xtUserLogin.setUsername(userName);
                xtUserLogin.setLoginErrorCount(0);
                xtUserLogin.setLoginState(Constants.LOGIN_STATE_LOGIN);
                xtUserLogin.setLastLoginTime(new Date(System.currentTimeMillis()));
                xtUserLoginDao.insert(xtUserLogin);
            }else {
                xtUserLogin.setLoginErrorCount(0);
                xtUserLogin.setLoginState(Constants.LOGIN_STATE_LOGIN);
                xtUserLogin.setLastLoginTime(new Date(System.currentTimeMillis()));
                xtUserLoginDao.update(xtUserLogin);
            }


			session.put("user_name", qUser.getUserName()); // 用户帐号
			session.put("userid", qUser.getUserId()); // 用户ID
			session.put("cxqx", qUser.getCxqx()); // 用户查询权限
			session.put("dyqx", qUser.getDyqx());// 打印权限
			session.put("yhlx", qUser.getYhlx()); // 用户类型--内部用户写日志时需要
			session.put("djid", qUser.getDjid());
			session.put("quser", qUser);
			//session.put("dyfs", qU)
			clearTempDir();
			if ("1".equals(qUser.getYhlx())) {
				//xuning modify begin 20190329,changed,xt_user no longer used
//				User user = UserDao.loadById(qUser.getUserId());
//				session.put("gxdw", user.getGxdwdm()); //管辖机构
//				session.put("djjg", user.getDjjg()); //登记机构
				QEkUser qEkUser = QEkUserDao.load(qUser.getUserId());

				session.put("gxdw", qEkUser.getGxdw());
				session.put("djjg",qEkUser.getUnit());
                String gxdwBxj = qEkUser.getGxdw();
				if(gxdwBxj!=null){
                    while (gxdwBxj.endsWith("00")){
                        gxdwBxj = gxdwBxj.substring(0,gxdwBxj.length()-2);
                    }
                    gxdwBxj = gxdwBxj+"%";
                }else{
				    gxdwBxj = "%";
                }
				session.put("gxdwBxj",gxdwBxj);
				session.put("spqx",qEkUser.getSpqx());
				//xuning modify end
				return "queryQy";
			} else {
				return "queryQyEk";
			}
		}
		if("logout".equals(action)){
			session.clear();
			session.remove("user_name");
			return "logout";
		}
		if("jdLogin".equals(action)){
			//tipInfo = "用户名密码错误";
			return "login";
		}
		return "error";
	}

	private void clearTempDir() {
		// //删除临时目录，创建当天的目录
		FileManager filemanager = new FileManager();

		// 创建当天的日期目录 yyyymmdd的格式
		SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMMdd");
		Date mydate = new Date();
		String dateStr = myFormatter.format(mydate);
		String path = ServletActionContext.getServletContext().getRealPath("./");
		String strAbsPath = new java.io.File(path).getAbsolutePath();
		java.io.File f = new java.io.File(strAbsPath + "/" + "tif" + "/" + dateStr);
		if (!f.exists()) {
			f.mkdir();
		}
		java.io.File flist = new java.io.File(strAbsPath + "/" + "tif" + "/");
		java.io.File[] subs = flist.listFiles();
		if (subs != null) {
			for (int i = 0; i <= subs.length - 1; i++) {
				if (subs[i].isDirectory()) {
					if (!(subs[i].getPath().equals(strAbsPath + "/" + "tif" + "/" + dateStr))) {
                        filemanager.delAll(subs[i], ""); // 递归删除子文件夹内容
                    }
				}
			}
		}
	}

	/**
	 * @return the userName
	 */
	public String getUserName() {
		return userName;
	}

	/**
	 * @param userName
	 *            the userName to set
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}

	/**
	 * @return the passWord
	 */
	public String getPassWord() {
		return passWord;
	}

	/**
	 * @param passWord
	 *            the passWord to set
	 */
	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}

	/**
	 * @return the action
	 */
	public String getAction() {
		return action;
	}

	/**
	 * @param action
	 *            the action to set
	 */
	public void setAction(String action) {
		this.action = action;
	}

	/**
	 * @return the tipInfo
	 */
	public String getTipInfo() {
		return tipInfo;
	}

	/**
	 * @param tipInfo
	 *            the tipInfo to set
	 */
	public void setTipInfo(String tipInfo) {
		this.tipInfo = tipInfo;
	}

	public String getCaptcha() {
		return captcha;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

    public boolean isShowCaptcha() {
        return showCaptcha;
    }

    public void setShowCaptcha(boolean showCaptcha) {
        this.showCaptcha = showCaptcha;
    }
}
